package com.bp.project.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.bp.common.constant.HttpStatus;
import com.bp.common.exception.CustomException;
import com.bp.common.utils.DateUtils;
import com.bp.common.utils.StringUtils;
import com.bp.common.utils.file.MimeTypeUtils;
import com.bp.framework.config.ServerConfig;
import com.bp.framework.util.SecurityUtils;
import com.bp.project.EnumProjectStatus;
import com.bp.project.EnumStageStatus;
import com.bp.project.domain.BizStage;
import com.bp.project.domain.BizStageContent;
import com.bp.project.service.IBizStageContentService;
import com.bp.project.service.IBizStageService;
import com.bp.system.domain.LoginUser;
import com.bp.system.domain.SysFileDomain;
import com.bp.system.domain.SysFileIndex;
import com.bp.system.service.ISysFileService;
import com.bp.system.service.ISysUserService;
import com.bp.system.service.ISysFileIndexService;
import org.apache.commons.collections4.CollectionUtils;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bp.common.annotation.Log;
import com.bp.common.core.controller.BaseController;
import com.bp.common.core.domain.AjaxResult;
import com.bp.common.enums.EnumBusinessType;
import com.bp.project.domain.BizProject;
import com.bp.project.service.IBizProjectService;
import com.bp.common.utils.poi.ExcelUtil;
import com.bp.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 项目工程信息Controller
 * 
 * @author shaominjie
 * @date 2021-01-18
 */
@RestController
@RequestMapping("/project/project")
@Transactional(rollbackFor = Exception.class)
public class BizProjectController extends BaseController {
    @Resource
    private IBizProjectService bizProjectService;
    @Resource
    private IBizStageService stageService;
    @Resource
    private IBizStageContentService stageContentService;
    @Resource
    private ISysUserService userService;
    @Resource
    private ISysFileIndexService userFileIndexService;
    @Resource
    private ISysFileService fileService;
    @Resource
    private ServerConfig serverConfig;
    /**
     * 查询项目工程信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(BizProject bizProject,Integer projectStatus, Integer days) {
        startPage();
        // 状态过滤
        if(projectStatus != null){
            StringBuilder sqlString = new StringBuilder();
            switch (projectStatus){
                case 1:
                    // 未招标
                    sqlString.append(" and ( bid_company is null or bid_company ='' ) ");
                    break;
                case 2:
                    // 未完成
                    sqlString.append(" and  status <>  ").append(EnumProjectStatus.FINISH.getStep());
                    break;
                case 3:
                    // 已完成
                    sqlString.append(" and  status =  ").append(EnumProjectStatus.FINISH.getStep());
                    break;
                case 4:
                    // 即将超期
                    sqlString.append(" and  complete_time <  '").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,DateUtils.getDayEnd(DateUtils.getDayAfter(new Date(),days==null?7:days)))).append("' ")
                            .append(" and complete_time > '").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,DateUtils.getDayEnd(new Date()))).append("' ");
                    break;
                case 5:
                    // 已超期
                    sqlString.append(" and  complete_time <  '").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date())).append("' ");
                    break;
                default:
                    break;
            }
            bizProject.getParams().put("projectStatus",sqlString.toString());
        }
        List<BizProject> list = bizProjectService.selectList(bizProject);
        return getDataTable(list);
    }

    /**
     * 导出项目工程信息列表
     */
    @Log(title = "项目工程信息", businessType = EnumBusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(BizProject bizProject) {
        List<BizProject> list = bizProjectService.selectList(bizProject);
        ExcelUtil<BizProject> util = new ExcelUtil<BizProject>(BizProject.class);
        return util.exportExcel(list, "project");
    }

    /**
     * 获取项目工程信息详细信息
     */
    @GetMapping(value = "/{projId}")
    public AjaxResult getInfo(@PathVariable("projId") Long projId) {
        return AjaxResult.success(bizProjectService.selectById(projId));
    }

    /**
     * 新增项目工程信息
     */
    @Log(title = "项目工程信息", businessType = EnumBusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizProject bizProject) {
        LoginUser user = SecurityUtils.getLoginUser();
        bizProject.setCreateBy(user.getUser().getUserName());
        int num =bizProjectService.insert(bizProject);
        if(num >0){
            //  新增阶段
            int numEx = stageService.startProject(bizProject);
            if(numEx<=0) {
                throw new CustomException("系统异常");
            }
        }
        return toAjax(num);
    }

    /**
     * 修改项目工程信息
     */
    @Log(title = "项目工程信息", businessType = EnumBusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizProject bizProject) {
        LoginUser user = SecurityUtils.getLoginUser();
        bizProject.setUpdateBy(user.getUser().getUserName());
        return toAjax(bizProjectService.update(bizProject));
    }

    /**
     * 删除项目工程信息
     */
    @Log(title = "项目工程信息", businessType = EnumBusinessType.DELETE)
	@DeleteMapping("/{projIds}")
    public AjaxResult remove(@PathVariable Long[] projIds) {
        int num = bizProjectService.deleteByIds(projIds);
        if(num >0) {
           // todo  为防止意外 暂时不做删除
        }

        return toAjax(num);
    }


    /**
     * 查询项目工程信息列表
     */
    @GetMapping("/detailList/{projId}")
    public AjaxResult list(@PathVariable("projId") Long projId) {
        List<BizStage> list = stageService.selectByProjId(projId);
        if(CollectionUtils.isNotEmpty(list)){
            Map<String,String> userName2nickNameMap = userService.userName2NickName();
            List<BizStageContent> stageContentList = stageContentService.selectByProjId(projId);

            for(BizStage item :list){
                List<BizStageContent> contentList = new ArrayList<>();
                for(BizStageContent tmp :stageContentList){
                    tmp.setUserName(userName2nickNameMap.get(tmp.getCreateBy()));
                    if(tmp.getStageId().equals(item.getStageId())){
                        if(CollectionUtils.isNotEmpty(tmp.getFileDomains())){
                            for(SysFileDomain file :tmp.getFileDomains()){
                                file.setUserName(userName2nickNameMap.get(file.getCreateBy()));
                            }
                        }
                        contentList.add(tmp);
                    }
                }
                item.setContentList(contentList);
            }
        }
        AjaxResult result = AjaxResult.success(list);
        return result;
    }

    @PostMapping("/stage/upload")
    public AjaxResult uploadFile(MultipartFile file, Long indexId,Long stageId) throws Exception {
        LoginUser user = SecurityUtils.getLoginUser();
        if(user == null) {
            throw new CustomException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
        }
        SysFileIndex fileIndex = userFileIndexService.selectById(indexId);
        if(fileIndex == null || fileIndex.getIndexId() == null){
            throw new CustomException("目录不存在");
        }

        try {
            // 暂不允许同目录下同名文件存在
            SysFileDomain fileDb = fileService.selectByFileName(fileIndex.getIndexId(),file.getOriginalFilename());
            if(fileDb !=null && fileDb.getFileId() != null) {
                throw new CustomException("存在同名文件");
            }

            // 上传文件路径 fileIndex.getFilePath()
            // 上传并返回新文件名称
            String fileName = fileService.upload(fileIndex.getFilePath(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
            String url = serverConfig.getUrl() + fileName;
            // 数据保存数据库
            SysFileDomain fileDomain = new SysFileDomain();
            fileDomain.setIndexId(fileIndex.getIndexId());
            fileDomain.setFileName(file.getOriginalFilename());
            fileDomain.setFileSize(file.getSize());
            fileDomain.setFilePath(fileIndex.getFilePath()+"/"+file.getOriginalFilename());
            fileDomain.setCreateTime(new Date());
            fileDomain.setCreateBy(user.getUsername());
            fileService.insert(fileDomain);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            ajax.put("file", fileDomain);
            return ajax;
        }
        catch (Exception e) {
            throw new CustomException(e.getMessage());
        }
    }
    @PostMapping("/stage/addStageContent")
    public AjaxResult addStageContent(@RequestBody BizStageContent content){
        content.setCreateTime(new Date());
        content.setCreateBy(SecurityUtils.getUsername());
        return toAjax(stageContentService.insert(content));
    }
    @GetMapping("/stage/finish/{stageId}")
    public AjaxResult finish(@PathVariable("stageId") Long stageId){
        BizStage stage  = stageService.selectById(stageId);
        BizStage nextStage = null;
        if(stage != null ) {
            BizProject project = bizProjectService.selectById(stage.getProjId());
            List<BizStage> stageList = stageService.selectByProjId(stage.getProjId());
            // 进行中的可以下一步
            if(EnumStageStatus.PROCESS.getKey().equals(stage.getStageStatus())){
                for(BizStage item : stageList) {
                    if(item.getStageStep() == stage.getStageStep()+1){
                        nextStage = item;
                        break;
                    }
                }
            }
            if(nextStage == null){
                //没有下一步
                stage.setStageStatus(EnumStageStatus.FINISH.getKey());
                project.setCurrentStage(99);
                project.setStatus(EnumProjectStatus.FINISH.getStep());
                bizProjectService.update(project);
            }else{
                nextStage.setStageStatus(EnumStageStatus.PROCESS.getKey());
                stage.setStageStatus(EnumStageStatus.SUCCESS.getKey());
                stageService.update(nextStage);
                project.setCurrentStage(nextStage.getStageStep());
                bizProjectService.update(project);
            }

        }
        return toAjax(stageService.update(stage));
    }

    @GetMapping("/allList")
    public AjaxResult allList(BizProject bizProject) {
        List<BizProject> list = bizProjectService.selectList(bizProject);
        return AjaxResult.success(list);
    }
    /**
     * 查询项目工程信息列表
     */
    @GetMapping("/getProjectFile")
    public TableDataInfo getProjectFile(BizProject bizProject, SysFileDomain fileDomain, Integer withChild) {
        startPage();
        BizProject project = bizProjectService.selectById(bizProject.getProjId());
        if(project == null || project.getProjId() == null){
            return getDataTable(new ArrayList<>());
        }
        List<BizStageContent> contentList = stageContentService.selectByProjId(project.getProjId());
        StringBuilder str = new StringBuilder();
        if(CollectionUtils.isNotEmpty(contentList)){
            for (BizStageContent item : contentList) {
                if(StringUtils.isNotEmpty(item.getFileIds())) {
                    str= str.append(item.getFileIds()).append(",");
                }
            }
        }
        if(StringUtils.isEmpty(str.toString())){
            return getDataTable(new ArrayList<>());
        }
        if(fileDomain.getIndexId() == null){
            return getDataTable(new ArrayList<>());
        }
        List<SysFileDomain> list;
        if(withChild == null || withChild == 0){
            list = fileService.selectListWithChildEx(fileDomain,str.toString());
        }else{
            list = fileService.selectListEx(fileDomain,str.toString());
        }
        return getDataTable(list);
    }
}
